//
//  FileUploader.swift
//  swift_review
//
//  Created by Andrew on 2024/11/27.
//

import Foundation
import UIKit

class FileUploader {
    
    // 定义上传函数
    class func uploadFiles(images: [UIImage]?, videos: [URL]?, to url: URL, completion: @escaping (Result<String, Error>) -> Void) {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("multipart/form-data; boundary=\(UUID().uuidString)", forHTTPHeaderField: "Content-Type")
        
        let boundary = UUID().uuidString
        var body = Data()
        
        // 处理图片
        if let images = images {
            for image in images {
                if let imageData = image.jpegData(compressionQuality: 0.8) {
                    body.append("--\(boundary)\r\n")
                    body.append("Content-Disposition: form-data; name=\"images[]\"; filename=\"\(UUID().uuidString).jpg\"\r\n")
                    body.append("Content-Type: image/jpeg\r\n\r\n")
                    body.append(imageData)
                    body.append("\r\n")
                }
            }
        }
        
        // 处理视频
        if let videos = videos {
            for videoURL in videos {
                if let videoData = try? Data(contentsOf: videoURL) {
                    body.append("--\(boundary)\r\n")
                    body.append("Content-Disposition: form-data; name=\"videos[]\"; filename=\"\(videoURL.lastPathComponent)\"\r\n")
                    body.append("Content-Type: video/mp4\r\n\r\n")
                    body.append(videoData)
                    body.append("\r\n")
                }
            }
        }
        
        // 结束边界
        body.append("--\(boundary)--\r\n")
        
        // 设置请求体
        request.httpBody = body
        
        // 使用URLSession上传数据
        let task = URLSession.shared.uploadTask(with: request, from: body) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            if let data = data, let responseString = String(data: data, encoding: .utf8) {
                completion(.success(responseString))
                print("上传成功")
            } else {
                completion(.failure(NSError(domain: "UploadError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred"])))
            }
        }
        
        task.resume()
    }
}

// 扩展Data，便于处理multipart/form-data请求体
extension Data {
    mutating func append(_ string: String) {
        if let data = string.data(using: .utf8) {
            append(data)
        }
    }
}

